<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\Perk;
use app\common\model\user\LevelOrder;
use app\common\model\user\PerkGrant;
use Exception;
use think\Db;

/**
 * 定时任务接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function code(){
        $userAll=Db::name("user")->select();
        if($userAll){
           foreach ($userAll as $k=>$v){
               $auth=new Auth();
               $code_url=$auth->createWxCode($v["id"]);
               if($code_url["code"]==1){
                   Db::name("user")->where(["id"=>$v["id"]])->update(["code"=>$code_url["data"]]);
               }
           }
            echo "success";
        }
    }
    /**
     * 发放补贴金额
     *
     */
    public function perk()
    {
        //发放补贴现金 start
        $order=LevelOrder::where("residue_money > 0 and state='2'")
            ->where("DATE_FORMAT(FROM_UNIXTIME(granttime), '%Y-%m-%d') != CURDATE() or granttime=0")
            ->select();
        $perk_data=[];
        $user_data=[];
        $update=[];
        $time=time();
        $userModel=new \app\common\model\User();
        if(!empty($order)){
            Db::startTrans();
            try {
                foreach ($order as $k=>$v){
                    $perk_data[$k]=[
                        "money"=>$v["daily_money"],
                        "user_id"=>$v["user_id"],
                        "level_id"=>$v["level_id"],
                        "level_order_id"=>$v["id"],
                        "createtime"=>$time,
                        "type"=>$v["type"],
                    ];
                    $update[$k]=[
                        "id"=>$v["id"],
                        "residue_money"=>$v["residue_money"]-$v["daily_money"],
                        "granttime"=>$time,
                    ];
                    $user=$userModel->get($v["user_id"]);
                    if(!empty($user)){
                        $user->setInc("perk_money",$v["daily_money"]);
                        //2023-12-18 新增 start
                        $grant=PerkGrant::where(["id"=>$v["grant_id"]])->find();
                        if($grant){
                            $grant->setDec("residue_money",$v["daily_money"]);
                        }
                    }
                    /*$after = function_exists('bcadd') ? bcadd($user["perk_money"]??0, $v["daily_money"], 2) : $user["perk_money"]??0 + $v["daily_money"];
                    $user_data[$k]=[
                        "id"=>$v["user_id"],
                        "perk_money"=>$after,
                    ];*/
                    //2023-12-18 新增 end
                }
                //新增发放记录
                if(!empty($perk_data)){
                    $model=new Perk();
                    $model->saveAll($perk_data);
                }
                //修改订单记录表
                if(!empty($update)){
                    $model=new LevelOrder();
                    $model->saveAll($update);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        //发放补贴现金 end

        //检测补贴金额是否过期 start
        $user=\app\common\model\User::where("perk_money >0")->select();
        if(!empty($user)){
            foreach ($user as $v){
                $order=LevelOrder::where(["state"=>'2',"user_id"=>$v["id"]])
                    ->where("end_granttime <".time())
                    ->where("is_ending",0)
                    ->sum("subsidy_money-residue_money");
                    // 将订单状态更改为已经处理的订单
                    LevelOrder::where(["state"=>'2',"user_id"=>$v["id"]])
                        ->where("end_granttime <".time())
                        ->where("is_ending",0)->update([
                            'is_ending'=> 1
                        ]);
                if(!empty($order) && $order>0){
                    $order_no="xjbtgqql".time();
                    $model=new \app\common\model\User();
                    $model->perkMoney(-$order,$v["id"],"现金补贴过期清理",0,$order_no);
                    $grant_id=LevelOrder::where(["user_id"=>$v["id"],"state"=>2,"type"=>1])->where("end_granttime <".time())->column("grant_id");
                    LevelOrder::where(["user_id"=>$v["id"],"state"=>2])->where("end_granttime <".time())->update(["residue_money"=>0]);
                    if(!empty($grant_id)){
                        PerkGrant::where('FIND_IN_SET("' . $v["id"] . '", user_ids)')
                            ->whereIn("id",$grant_id)
                            ->where("end_granttime <".time())->update(["residue_money"=>0]);
                    }
                }
            }
        }
        //检测补贴金额是否过期 end

        //检测佣金是否到账 start
        // 查询是否有退款
        $config = get_addon_config('wanlshop');
        $day= $config["order"]["commission_day"] ?? 7;//确认收获后X天佣金到账
        $date = strtotime('-'.($day).' day',time());
        $receiving = model('app\api\model\wanlshop\Order')
            ->field("GROUP_CONCAT(DISTINCT id) id")
            ->where([
                'taketime' => ['<', $date]
            ])
            ->whereIn("state",['6','4'])
            ->where("id not in (".model('app\api\model\wanlshop\Refund')
                    ->field("order_id")
                    ->where([ 'state' => 4, 'order_type' => 'goods'])->fetchSql()
                    ->select().")")
            ->find();
        if(!empty($receiving) && !empty($receiving["id"])){
            $distribution= model('app\common\model\Distribution')
                ->where([
                    'type'=>2,
                    'status'=>0,
                ])->whereIn("order_id",$receiving["id"])->select();
            if(!empty($distribution)){
                $update=[];
                $Usermodel=new \app\common\model\User();
                foreach ($distribution as $k=>$v){
                    /*controller('addons\wanlshop\library\WanlPay\WanlPay')
                        ->money(+$v['price'], $v['user_id'], '订单确认收货', 'okorder', $v['order_no']);*/
                    //2023-11-9 lina start
                    if($v["identity"]==2){
                        //区域代理--给区域代理钱包加钱
                        $Usermodel->region_commission($v["money"],$v["commiss_user_id"],$v["remark"],$v["order_id"],$v["order_no"],$v["identity"]);
                    }else{
                        $Usermodel->commission($v["money"],$v["commiss_user_id"],$v["remark"],$v["order_id"],$v["order_no"],$v["identity"]);
                    }
                    //2023-11-9 lina end
                    $update[]=[
                        "id"=>$v["id"],
                        "status"=>1,
                    ];
                }
                if (!empty($update)){
                    model('app\common\model\Distribution')->saveAll($update);
                }
            }
        }
        //检测佣金是否到账 end
        $this->success('成功');

        //修改体验卡会员到期状态
        \app\common\model\User::where(["level_id"=>1])->where("level_time is not null and level_time<=".strtotime("Y-m-d",time()))->update(["level_id"=>0]);
    }
}
